﻿using NetFramework;
using NetFramework.AsyncSocketClient;
using SystemModule;

namespace M2Server
{
    public class DBEngine
    {
        public IClientScoket DBSocket = null;

        public DBEngine()
        {
            DBSocket = new IClientScoket();
            DBSocket.OnConnected += new DSCClientOnConnectedHandler(DBSocketConnect);
            DBSocket.ReceivedDatagram += new DSCClientOnDataInHandler(DBSocketRead);
        }

        public void Start()
        {
            Connected();
        }

        public void Connected()
        {    
            DBSocket.Connect(M2Share.DBEngine.DBSocket.Address, M2Share.DBEngine.DBSocket.Port);
        }
        
        /// <summary>
        /// 数据库连接成功，显示远程IP及端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DBSocketConnect(object sender, DSCClientConnectedEventArgs e)
        {
            M2Share.MainOutMessage("数据库服务器[" + DBSocket.Address + ':' + DBSocket.Port + "]连接成功...");
            M2Share.g_nSaveRcdErrorCount = 0;
        }

        /// <summary>
        /// 数据库连接错误
        /// </summary>
        private void DBSocketError(object sender, DSCClientConnectedEventArgs e)
        {
            M2Share.MainOutMessage("[Error]:DBSocketError");
        }

        /// <summary>
        /// 读取数据库数据,即DBserver.exe 回传的数据
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Socket"></param>
        private unsafe void DBSocketRead(object sender, DSCClientDataInEventArgs e)
        {
            string tStr = string.Empty;
            HUtil32.EnterCriticalSection(M2Share.UserDBSection);
            try
            {
                fixed (byte* pb = e.Data)
                {
                    tStr = HUtil32.SBytePtrToString((sbyte*)pb, 0, e.Data.Length);
                }
                M2Share.g_Config.sDBSocketRecvText = M2Share.g_Config.sDBSocketRecvText + tStr;// ReceiveText表示收到的文本内容
                if (!M2Share.g_Config.boDBSocketWorking)
                {
                    M2Share.g_Config.sDBSocketRecvText = "";
                }
            }
            finally
            {
                HUtil32.LeaveCriticalSection(M2Share.UserDBSection);
            }
        }
    }
}
